package com.qzsoft.fileServers.controller;

import com.qzsoft.fileServers.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Api(value="/file", tags="本地文件服务接口")
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    public FileService fileService;

    @ApiOperation(value = "保存小于100M文件", notes = "保存文件并返回ID")
    @PostMapping(value = "/small", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> saveSmall(@RequestParam(value = "file", required = true) MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        try {
            map.put("success",true);
            map.put("id",fileService.saveSmall(file));
        } catch (Exception e) {
            map.put("success",false);
            map.put("msg",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    @ApiOperation(value = "保存大于100M文件", notes = "保存文件并返回ID")
    @PostMapping(value = "/big", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> saveBig(@RequestParam(value = "file", required = true) MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        try {
            map.put("success",true);
            map.put("id",fileService.saveBig(file));
        } catch (Exception e) {
            map.put("success",false);
            map.put("msg",e.getMessage());
            e.printStackTrace();
        }
        return map;
    }

    @ApiOperation(value = "下载文件", notes = "根据ID返回文件流下载")
    @GetMapping(value = "/{id}")
    public void get(@PathVariable String id, HttpServletResponse res) {
        Map<String,Object> map = new HashMap<>();
        try {
            fileService.get(id,res);
            map.put("success",true);
        } catch (Exception e) {
            map.put("success",false);
            map.put("msg",e.getMessage());
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "删除文件", notes = "根据ID删除对应的文件")
    @DeleteMapping(value = "/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String,Object> delete(@PathVariable String id) {
        Map<String,Object> map = new HashMap<>();
        try {
            fileService.delete(id);
            map.put("success",true);
        } catch (Exception e) {
            map.put("success",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }
}
